#coding=utf-8
import requests,json,urllib
import re
import admin_login_api
import random
import mysql_password
from upload_photo import uploadPhoto

#发布文章的接口：手机号、文章标题、文章内容、栏目分类（8为互联视界，9为科学+，10为行业风向，11为掘金宝典，12为朵云社区）
def upload_news(mobile,title,content,articleCategoryId,showKeywords):
    user_id = mysql_password.password(mobile)[1]   #通过接口获取user_id
    NickName = mysql_password.password(mobile)[2]  #通过接口获取昵称
    s = requests.session()
    wechatQrcodeUrl = uploadPhoto("WX.png")   #通过上传图片接口获得微信二维码的url
    randomNum = str(random.randint(1, 14))
    photoUrl = uploadPhoto(randomNum+".png")  #通过上传图片接口获得图片的url
    headers = admin_login_api.admin_login('17700010005')   #调用登录函数进行登录获取headers
    if user_id == '0':  #输入自定义用户
        if showKeywords == '1':  #显示关键字
            data = ({"keywords": ["国产","新机","发布"], "resourcesInfo":{"image_list":[photoUrl],"layout_style":"RIGHT_SIDE"},
                     "mediaInfo":{"link_url":"http://community-fs-api-test.gdgyun.com/uploads/storage/medias/1501276f56c3b333a570bfb72c58447999aa72ce.mp4","type":"VIDEO"},
                     "sectionMediaInfo":{"link_url":"http://community-fs-api-test.gdgyun.com/uploads/storage/medias/8cfb0c59fed0f5a35b05dac9ff66dce83f96ebb6.mp4","type":"VIDEO"},"title": title, "id": "",
                     "postedBy": mobile, "content": content, "articleCategoryId": articleCategoryId, "shareSummary":"分享摘要！分享摘要！分享摘要！分享摘要！",
                     "wechatNumber":"测试公众号","wechatQrCodeUrl":wechatQrcodeUrl,
                     "showKeywords":1})
        if showKeywords == '0':  #不显示关键字
            data = ({"keywords": ["经济", "创新", "房地产"], "resourcesInfo": {"image_list": [photoUrl],"layout_style": "RIGHT_SIDE"},
                     "mediaInfo": {"link_url": "http://community-fs-api-test.gdgyun.com/uploads/storage/medias/1501276f56c3b333a570bfb72c58447999aa72ce.mp4","type": "VIDEO"},
                     "sectionMediaInfo": {"link_url": "http://community-fs-api-test.gdgyun.com/uploads/storage/medias/8cfb0c59fed0f5a35b05dac9ff66dce83f96ebb6.mp4","type": "VIDEO"}, "title": title, "id": "",
                     "postedBy": mobile, "content": content, "articleCategoryId": articleCategoryId,
                     "shareSummary": "分享摘要！分享摘要！分享摘要！分享摘要！",
                     "wechatNumber": "测试公众号",
                     "wechatQrCodeUrl": wechatQrcodeUrl,
                     "showKeywords": 0})
        upload = s.post('http://community-bms-api-test.gdgyun.com/mgt/api/community/home/article/add', json=data,headers=headers)
        articleId_index = s.get('http://community-bms-api-test.gdgyun.com/mgt/api/community/home/article/list?title=' + str(title),headers=headers)  # 获取到新建文章的ID号
        articleId = articleId_index.json()["data"]["list"][0]["id"]
        online = s.put('http://community-bms-api-test.gdgyun.com/mgt/api/community/home/article/online/' + str(articleId) + '/true')  # 将该文章上线
    else:  #用户为社区用户
        if showKeywords == '1':  #显示关键字
            data = ({"keywords": ["财经","朵云","云社区"], "resourcesInfo":{"image_list":[photoUrl],"layout_style":"RIGHT_SIDE"},
                     "mediaInfo":{"link_url":"http://community-fs-api-test.gdgyun.com/uploads/storage/medias/1501276f56c3b333a570bfb72c58447999aa72ce.mp4","type":"VIDEO"},
                     "sectionMediaInfo":{"link_url":"http://community-fs-api-test.gdgyun.com/uploads/storage/medias/8cfb0c59fed0f5a35b05dac9ff66dce83f96ebb6.mp4","type":"VIDEO"}, "title": title, "id": "", "userId": user_id,
                     "postedBy": NickName, "content": content, "articleCategoryId": articleCategoryId,
                     "shareSummary": "分享摘要！分享摘要！分享摘要！分享摘要！",
                     "wechatNumber": "测试公众号",
                     "wechatQrCodeUrl": wechatQrcodeUrl,
                     "showKeywords": 1
                     })
        if showKeywords == '0':  #不显示关键字
            data = ({"keywords": ["投资","利润","贸易"], "resourcesInfo":{"image_list":[photoUrl],"layout_style":"RIGHT_SIDE"},
                     "mediaInfo":{"link_url":"http://community-fs-api-test.gdgyun.com/uploads/storage/medias/1501276f56c3b333a570bfb72c58447999aa72ce.mp4","type":"VIDEO"},
                     "sectionMediaInfo":{"link_url":"http://community-fs-api-test.gdgyun.com/uploads/storage/medias/8cfb0c59fed0f5a35b05dac9ff66dce83f96ebb6.mp4","type":"VIDEO"}, "title": title, "id": "", "userId": user_id,
                     "postedBy": NickName, "content": content, "articleCategoryId": articleCategoryId,
                     "shareSummary": "分享摘要！分享摘要！分享摘要！分享摘要！",
                     "wechatNumber": "测试公众号",
                     "wechatQrCodeUrl": wechatQrcodeUrl,
                     "showKeywords": 0
                     })
        upload = s.post('http://community-bms-api-test.gdgyun.com/mgt/api/community/home/article/add', json=data,headers=headers)
        articleId_index = s.get('http://community-bms-api-test.gdgyun.com/mgt/api/community/home/article/list?title='+str(title),headers=headers)  # 获取到新建文章的ID号
        articleId = articleId_index.json()["data"]["list"][0]["id"]
        online = s.put('http://community-bms-api-test.gdgyun.com/mgt/api/community/home/article/online/' + str(articleId) + '/true',headers=headers)  # 将该文章上线
    return upload.text,articleId

#获取新闻接口
def News(mobile,articleCategoryId,showKeywords):
    try:
        s = requests.session()
        index = s.get('https://news.baidu.com/')  # 进入百度新闻网站
        url = re.findall(r'a href="(.+)"', index.text)  # 获得新闻的url
        num = len(url)
        for i in range(0, int(num), 1):
            try:
                id = random.randint(0, int(num))
                index_news = s.get(url[id])
                #print str(url[id])
                title = re.findall(r'<title>(.+)</title>', index_news.text)[0]  # 获得新闻的标题
                content = re.findall(r'<p>(.+)</p>', index_news.text)  # 获得文章的内容
                article = ''.join(content)
                if article == '':
                    print u'重新获取文章'
                    continue
                else:
                    result_list = upload_news(mobile, title, article, articleCategoryId,showKeywords)  # 8为互联视界，9为科学+，10为行业风向，11为掘金宝典，12为朵云社区
                    msg = result_list[0]
                    articleId = result_list[1]
                    break
            except:
                continue

        msg = msg + u'，文章标题是：' + str(title)
        return msg,articleId

    except:
        msg = u'文章创建失败，请再次执行'
        return msg,msg


if __name__ =='__main__':
    s = requests.session()
    index = s.get('https://news.baidu.com/')  # 进入腾讯新闻网站
    url = re.findall(r'a href="(.+)"', index.text)  # 获得新闻的url
    num = len(url)
    print num
    for i in range(0, int(num), 1):
        try:
            id = random.randint(0, int(num))
            index_news = s.get(url[id])
            print str(url[id])
            title = re.findall(r'<title>(.+)</title>', index_news.text)[0]  # 获得新闻的标题
            content = re.findall(r'<p>(.+)</p>', index_news.text)  # 获得文章的内容
            article = ''.join(content)
        except:
            continue
        if article == '':
            print u'重新获取文章'
            continue
        else:
            print title
            print article
            break

    # if article == '':
    #     index_news = s.get(url[0])
    #     title = re.findall(r'<title>(.+)</title>', index_news.text)[0]  # 获得新闻的标题
    #     content = re.findall(r'<p class="one-p">(.+)</p>', index_news.text)  # 获得文章的内容
    #     article = ''.join(content)
    #     print u'重新获取文章'+article
    # else:
    #     print article
    # print article
    #upload_news('17700010005',title,article,'11')   #8为互联视界，9为科学+，10为行业风向，11为掘金宝典，12为朵云社区




